package com.hefan.user.dao;

import com.hefan.user.bean.Denounce;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hbchen on 2016/9/28.
 */
@Repository
public class DenounceDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    private static String TABLE_NAME = "denounce";

    /**
     * 根据被举报人查询未处理批次记录
     * @param denouncedUserId
     * @return
     */
    public Denounce noHandlerDenounce(String denouncedUserId){


       String sql =  " select id from denounce where denounced_user_id = ? and status=0 ORDER BY id DESC LIMIT 1";
        try {
            return jdbcTemplate.queryForObject(sql, new DenounceRowMapper(), denouncedUserId);
        }catch (EmptyResultDataAccessException e){
            return  null;
        }
    }

    /**
     * 增加新的处理批次记录
     * @param record
     * @return
     */
    public int addNewDenounce(Denounce record){

        Map<String,Object> parameters =  new HashMap<String,Object>();
        parameters.put("denounced_user_id",record.getDenouncedUserId());
        String[] columns = parameters.keySet().toArray(new String[]{});
        SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(getJdbcTemplate().getDataSource())
                .usingColumns(columns)
                .withTableName(TABLE_NAME)
                .usingGeneratedKeyColumns("id");
        Number id = simpleJdbcInsert.executeAndReturnKey(parameters);
        record.setId(id.longValue());
        return id.intValue();
    }


    class DenounceRowMapper implements RowMapper<Denounce> {
        //rs为返回结果集，以每行为单位封装着
        public Denounce mapRow(ResultSet rs, int rowNum) throws SQLException {

                Denounce denounce = new Denounce();
                denounce.setId(rs.getLong("id"));
                return denounce;

        }

    }


}
